package com.moxie.ocr.ocr.idcard;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import com.moxie.ocr.R;
import com.moxie.ocr.network.MXLicDownloadManager;
import com.moxie.ocr.ocr.base.Card;
import com.moxie.ocr.ocr.base.MXGlobalVar;
import com.moxie.ocr.ocr.card.CardActivity;
import com.moxie.ocr.ocr.card.CardRecognizer;
import com.moxie.ocr.ocr.card.CardScanner;
import com.moxie.ocr.ocr.card.RecognizerInitFailException;
import com.moxie.ocr.ocr.utils.MXConstants;
import com.moxie.ocr.ocr.utils.MXImageUtils;
import com.moxie.ocr.ocr.utils.MXSDCardUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


public class IDCardActivity extends CardActivity {


    /**
     * 传入身份证识别模式
     * 类型为 {@link IDCardRecognizer.Mode}
     */
    public static final String EXTRA_RECOGNIZE_MODE = "com.moxie.idcard.recognizeMode";

    /**
     * 传入需要识别的的身份证字段Mask {@link IDCardRecognizer#RECOGNIZE_FLAG_ALL}(default)
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_NAME}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_SEX}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_NATION}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_BIRTH}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_ADDR}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_ID}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_AUTHORITY}
     * {@link IDCardRecognizer#RECOGNIZE_FLAG_VALIDITY}
     */
    public static final String EXTRA_RECOGNIZE_FLAG = "com.moxie.idcard.recognizeFlag";

    private IDCardRecognizer.Mode mRecognizeMode;

    /**
     * 设置需要输出身份证人脸截图<br>
     * 输入类型为boolean，true表示要输出，false表示不需要输出<br>
     * 可以在{@link Activity#onActivityResult(int, int, Intent)}中使用<br>
     * data.getByteArrayExtra(CardActivity.EXTRA_IDCARD_FACE)获取JPEG字节数组
     */
    public static final String EXTRA_IDCARD_FACE = "com.moxie.idcard.face";



    /**
     * 身份证前面裁剪图
     */
    public static final String KEY_FRONT_CROP_BITMAP = "key_front_crop_bitmap";

    /**
     * 身份证前面裁剪框的图
     */
    public static final String KEY_FRONT_CAMERA_APERTURE_BITMAP = "key_front_camera_aperture_bitmap";

    /**
     * 身份证反面裁剪图
     */
    public static final String KEY_BACK_CROP_BITMAP = "key_back_crop_bitmap";

    /**
     * 身份证反面裁剪框的图
     */
    public static final String KEY_BACK_CAMERA_APERTURE_BITMAP = "key_back_camera_aperture_bitmap";

    /**
     * 身份证正面数据
     */
    public static final String KEY_FRONT_CARD_DATA = "key_front_card_data";

    /**
     * 身份证反面数据
     */
    public static final String KEY_BACK_CARD_DATA = "key_back_card_data";

    /**
     * 识别模式
     */
    public static final String KEY_SCAN_BOTH_MODE = "key_scan_mode";


    public boolean isBothModeFlag=false;


    private Intent mIntent = null;

    private Card mFrontIDCard;

    boolean isFront = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }




    protected void setRecognizeMode(IDCardRecognizer.Mode mode) {
        mRecognizeMode = mode;
        IDCardScanner idCardScanner = getIDCardScanner();
        if (idCardScanner != null) {
            idCardScanner.setRecognizerMode(mode);
        }
    }

    protected void setRecognizerFlag(int flag) {
        IDCardScanner idCardScanner = getIDCardScanner();
        if (idCardScanner != null) {
            idCardScanner.setRecognizerFlag(flag);
        }
    }

    @Override
    protected void refreshRightTitleBtnView() {
        // 相册默认就是不可见
        if(mScanIsManualRecognize) {
            // 拍照识别时 相册可见
            mTvTitleRight.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化IDCard扫描类
     *
     * @param context
     * @param currentFrameOrientation
     * @param isVertical
     * @return
     */
    @Override
    protected CardScanner initCardScanner(Context context, int currentFrameOrientation, boolean isVertical) {
        return new IDCardScanner(context, currentFrameOrientation);
    }

    @Override
    protected void createCardScan() {
        super.createCardScan();

        Intent intent = getIntent();
        if (intent != null) {
            IDCardRecognizer.Mode recognizeMode = (IDCardRecognizer.Mode) intent.getSerializableExtra(EXTRA_RECOGNIZE_MODE);
            isBothModeFlag = intent.getBooleanExtra(KEY_SCAN_BOTH_MODE,false);
            int recognizeFlag = intent.getIntExtra(EXTRA_RECOGNIZE_FLAG, IDCardRecognizer.RECOGNIZE_FLAG_ALL);
            setRecognizeMode(recognizeMode);
            setRecognizerFlag(recognizeFlag);
        }
    }

    private IDCardScanner getIDCardScanner() {
        IDCardScanner idCardScanner = null;
        CardScanner cardScanner = getCardScanner();
        if (cardScanner instanceof IDCardScanner) {
            idCardScanner = (IDCardScanner) cardScanner;
        }
        return idCardScanner;
    }

    @Override
    protected void processManualRecognize() {
        final Bitmap confirmBmp = MXGlobalVar.sCardBitmap;
        final Bitmap copyBitmap = MXImageUtils.copyBitmap(confirmBmp);

        if(confirmBmp == null || confirmBmp.isRecycled()) {
            Toast.makeText(IDCardActivity.this, "手动确认图片不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            IDCardRecognizer idCardRecognizer = new IDCardRecognizer(IDCardActivity.this);
            idCardRecognizer.setMode(mRecognizeMode);
            idCardRecognizer.setRecognizeFlag(IDCardRecognizer.RECOGNIZE_FLAG_ALL);

            idCardRecognizer.recognizeCard(confirmBmp, getScanIsInFrame(), new CardRecognizer.ICardRecognizeCallback() {

                @Override
                public void callback(com.moxie.ocr.ocr.base.Card card, Bitmap recognizeBitmap) {
                    // 将识别完后的卡信息添加到结果页
                    goToResultActivity(card, copyBitmap, recognizeBitmap,mRecognizeMode);
                }
            });
        } catch (RecognizerInitFailException e) {
            e.printStackTrace();
        }
    }


    // 重写这个方法来自定义检测到卡片后的处理方式
    @Override
    public void onCardDetected(Card card, Bitmap cameraApertureBitmap, Bitmap cropCardBitmap) {
        if (!isBothModeFlag){
            playVibrator();
            pauseCardScan();
            goToResultActivity(card, cameraApertureBitmap, cropCardBitmap,mRecognizeMode);
        }else{
            if (mIntent == null) {
                mIntent = new Intent();
            }
            // 处理过程中先暂停扫描(没必要 因为光开关相机的功夫都已经可以处理完了)
            // pauseCardScan();
            // 获取识别出的是哪一面
            MXOCRResult idCard = null;
            if (card instanceof MXOCRResult) {
                idCard = (MXOCRResult) card;
            }
            if (idCard != null) {
                if (isFront) {
                    isFront = false;
                    onTextUpdate("扫描成功", getResources().getColor(R.color.green));

                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            onTextUpdate("请将身份证反面放入扫描框内", Color.WHITE);
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, 1000);//“扫描成功”显示1秒

                    // 返回取景框图像
                    if (getIntent() != null && getIntent().getBooleanExtra(KEY_FRONT_CAMERA_APERTURE_BITMAP, true)) {
                        ByteArrayOutputStream scaledCardBytes = new ByteArrayOutputStream();
                        cameraApertureBitmap.compress(Bitmap.CompressFormat.JPEG, 80, scaledCardBytes);
//                        mIntent.putExtra(KEY_FRONT_CAMERA_APERTURE_BITMAP, scaledCardBytes.toByteArray());
                        idCard.setCameraApertureImage(scaledCardBytes.toByteArray());
                        try {
                            scaledCardBytes.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    //返回裁剪图
                    if (getIntent() != null && getIntent().getBooleanExtra(KEY_FRONT_CROP_BITMAP, true) && cropCardBitmap != null) {
                        ByteArrayOutputStream scaledCardBytesRectified = new ByteArrayOutputStream();
                        cropCardBitmap.compress(Bitmap.CompressFormat.JPEG, 80, scaledCardBytesRectified);
//                        mIntent.putExtra(KEY_FRONT_CROP_BITMAP, scaledCardBytesRectified.toByteArray());
                        idCard.setCropImage(scaledCardBytesRectified.toByteArray());
                        try {
                            scaledCardBytesRectified.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    // 返回头像裁剪图
                    if (cropCardBitmap!=null && mRecognizeMode==IDCardRecognizer.Mode.FRONT){
                        ByteArrayOutputStream scaledCardBytesRectified = new ByteArrayOutputStream();
                        int height = cropCardBitmap.getHeight();
                        int width = cropCardBitmap.getWidth();
                        Bitmap avatar = Bitmap.createBitmap(cropCardBitmap, width / 8 * 5, height / 7, width / 3, height / 5 * 3);
                        avatar.compress(Bitmap.CompressFormat.JPEG, 80, scaledCardBytesRectified);
                        idCard.setCropFaceImage(scaledCardBytesRectified.toByteArray());
                    }

                    mFrontIDCard = idCard;
                    // 识别正面完成，开启震动500毫秒
                    Vibrator vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);
                    vibrator.vibrate(500);
                    // 设置识别背面
                    setRecognizeMode(IDCardRecognizer.Mode.BACK);
                    // 继续扫描
                    resumeScanning();

                } else if (!isFront) {
                    // 扫描完背面，返回数据或进行下一步操作

                    // 返回原始图像
                    if (getIntent() != null && getIntent().getBooleanExtra(KEY_BACK_CAMERA_APERTURE_BITMAP, true)) {
                        ByteArrayOutputStream scaledCardBytes = new ByteArrayOutputStream();
                        cameraApertureBitmap = resizeImage(cameraApertureBitmap, 1280, 800);
                        cameraApertureBitmap.compress(Bitmap.CompressFormat.JPEG, 80, scaledCardBytes);
//                        mIntent.putExtra(KEY_BACK_CAMERA_APERTURE_BITMAP, scaledCardBytes.toByteArray());
                        idCard.setCameraApertureImage(scaledCardBytes.toByteArray());
                        try {
                            scaledCardBytes.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    // 返回裁剪图像
                    if (getIntent() != null && getIntent().getBooleanExtra(KEY_BACK_CROP_BITMAP, true) && cropCardBitmap != null) {
                        ByteArrayOutputStream scaledCardBytesRectified = new ByteArrayOutputStream();
                        cropCardBitmap.compress(Bitmap.CompressFormat.JPEG, 80, scaledCardBytesRectified);
//                        mIntent.putExtra(KEY_BACK_CROP_BITMAP,scaledCardBytesRectified.toByteArray());
                        idCard.setCropImage(scaledCardBytesRectified.toByteArray());
                        try {
                            scaledCardBytesRectified.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    mIntent.putExtra(KEY_FRONT_CARD_DATA, mFrontIDCard);
                    mIntent.putExtra(KEY_BACK_CARD_DATA, idCard);

                    playVibrator();
                    setResult(RESULT_CARD_INFO, mIntent);
                    finish();
                }
            }
        }
    }
}
